#!/bin/bash



PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
PATH=$PATH:/usr/lib/node_modules
export $PATH
DEFAULT_USER="parse"
parse_user=$DEFAULT_USER;
 
 
# Make sure only root can run our script
[[ $EUID -ne 0 ]] && echo -e "This script must be run as root!" && exit 1
apt-get update & apt-get upgrade -y;
 
# add an user with default name 'parse'.
pre_install(){
    clear
    echo;echo "-----------------------------------------------";echo;
    # create a user named 'parse' and run this script by the user
    read -p "Enter username(default: parse) : " username
    
    [ -z "$username" ] && echo "Input is empty, use default user name: parse." && username=$DEFAULT_USER
 
    egrep "^$username" /etc/passwd >/dev/null
    [ $? -eq 0 ] && echo "$username exists!" && return 1
 useradd -m $username -s /bin/bash
 [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
    parse_user=$username
}
 
install_mongo(){
    echo "install mongodb";
    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
    echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 main" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
    apt-get update
    apt-get install -y mongodb-org
}
 
install_parse(){
    echo ">> install parse server to user:$username";
    curl -sL https://deb.nodesource.com/setup_6.x -o nodesource_setup.sh
    chmod +x ./nodesource_setup.sh && ./nodesource_setup.sh
    apt-get install -y nodejs build-essential git
    npm install -g express --save
    npm install -g parse-server parse-dashboard pm2
    pm2 startup ubuntu -u $parse_user --hp /home/$parse_user/
}
 
start_sample(){
    echo "start sample parse app and parse dashborad."
    cd;
    wget https://dl.lidalao.com/parse-app-sample.js -O ./parse-app-sample.js;
    mv ./parse-app-sample.js /home/$parse_user;
    
    echo
    echo -e "Congratulations, Parse server install completed wihth a sample!"
    echo -e "Just run below commands to start the sample project:"
    echo -e "sudo $parse_user"
    echo -e "pm2 start parse-app-sample.js"
    echo -e "pm2 save"
    echo
    echo "Welcome to visit: https://lidalao.com"
    echo "Enjoy it!"
    echo
}
 
pre_install;
install_mongo;
install_parse;
start_sample;



